package com.xl98.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xl98.entity.Groups;
import com.xl98.entity.UserGroups;
import com.xl98.mapper.GroupsMapper;
import com.xl98.mapper.UserGroupsMapper;
import com.xl98.service.UserGroupsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ls
 * @since 2020-05-15
 */
@Service
public class UserGroupsServiceImpl extends ServiceImpl<UserGroupsMapper, UserGroups> implements UserGroupsService {
    @Autowired
    private UserGroupsMapper userGroupsMapper;
    @Autowired
    private GroupsMapper groupsMapper;

    @Override
    public boolean addUserGroups(UserGroups userGroups) {
        try{
            Groups groups = groupsMapper.selectOneById(userGroups.getGroupsId());
            if(groups.getUsersSum() >= groups.getUsersMaxNumber()){
                return false;
            }else{
                groups.setUsersSum(groups.getUsersSum()+1);
                groupsMapper.updateOne(groups);
                if(userGroupsMapper.insert(userGroups)>0) {
                    return true;
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return false;
    }

    @Override
    public boolean deleteUserGroups(UserGroups userGroups) {
        try{
            Groups groups = groupsMapper.selectOneById(userGroups.getGroupsId());
            QueryWrapper<UserGroups> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userGroups.getUserId());
            queryWrapper.eq("groups_id",userGroups.getGroupsId());
            if(userGroupsMapper.delete(queryWrapper)>0){
                groups.setUsersSum(groups.getUsersSum()-1);
                groupsMapper.updateOne(groups);
                return true;
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        return false;
    }
}
